import datetime
import time

from sqlalchemy import Column, Integer, String, Numeric, Unicode
from sqlalchemy.orm import mapper
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.exc import *

class ModelError(Exception):
   pass

Base = declarative_base()
class PkgInfo(Base):
   __tablename__ = u'pkg_info'

   pk = Column(Integer, primary_key = True)
   package = Column(Unicode(75), nullable = False)
   version = Column(Unicode(15), nullable = False)
   location = Column(Unicode(15), nullable = False)
   pkginfo = Column(Unicode(200), nullable = True)
   maintainer = Column(Unicode(255), nullable = False)
   pkgtags = Column(Unicode(500), nullable = True)
   lastupdate = Column(Numeric(11, 7), nullable = False)

   def __init__(self, Package, Version, Location, Maint,
         info = False, tags = False):
      super(PkgInfo, self).__init__()
      if Package:
         self.package = Package
      else:
         raise ModelError, "no package information provided!"

      if Version:
         self.version = Version
      else:
         raise ModelError, "no package version information provided!"

      if Location:
         self.location = Location
      else:
         raise ModelError, "no location information for package provided!"

      if Maint:
         self.maintainer = Maint
      else:
         raise ModelError, "no maintainer information for package provided!"

      if info:
         self.pkginfo = info

      if tags:
         self.pkgtags = tags

      self.lastupdate = time.time()

   def __str__(self):
      return "%s-%s" %(str(self.package), str(self.version))

   def __repr__(self):
      return repr(str(self))

   def __unicode__(self):
      return unicode(str(self))

   @property
   def update(self):
      return datetime.date.fromtimestamp(self.lastupdate)

def create(Engine):
   if Engine:
      try:
         Base.metadata.create_all(Engine)
      except OperationalError, message:
         raise ModelError, message
   else:
      raise ModelError, "no engined defined!"
